package com.jiezuo.auth.controller;

import com.jiezuo.common.base.BaseController;
import com.jiezuo.common.constant.SysConstant;
import com.jiezuo.common.util.StringUtil;
import com.jiezuo.common.util.VCodeUtil;
import com.jiezuo.common.util.ResultUtil;
import com.jiezuo.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @description 验证码管理
 * @author 庞留杰
 * @date 2020/7/23 18:03
 * @version V1.0
 **/
@Slf4j
@RequestMapping("/captcha")
@RestController
//验证码管理", tags = {"图形验证码管理接口"})
public class ImageController extends BaseController {

    //验证码有效时间(分钟)
    @Value("${auth.captcha-valid-time}")
    public String captchaValidTime;
    @Autowired
    private StringRedisTemplate redisTemplate;

    //初始化验证码", notes = "初始化验证码")
    @GetMapping("/init")
    public Result<String> init() {
        // 获取验证码，验证码字符个数
        String verifyCode = VCodeUtil.generateVerifyCode(4);
        String key = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        redisTemplate.opsForValue().set(SysConstant.REDIS_CAPTCHA + key, verifyCode, Integer.valueOf(captchaValidTime), TimeUnit.MINUTES);
        return new ResultUtil<String>().setData(key);
    }

    //验证码图片", notes = "获取并返回验证码图片")
    //(name = "key", value = "初始化验证码的返回值", dataType = "String", required = true, paramType = "path")
    @GetMapping("/draw/{key}")
    public void getImg(HttpServletResponse response, @PathVariable String key) throws IOException {
        String s = redisTemplate.opsForValue().get(SysConstant.REDIS_CAPTCHA + key);
        if(!StringUtil.isNotEmpty(s)){
            log.info("KEY已失效,请重新获取");
            return;
        }
        int w = 100, h = 30;
        VCodeUtil.outputImage(w, h, response.getOutputStream(), s);
    }

}
